<template>
  <div class="role-management">
    <el-card class="role-card">
      <template #header>
        <div class="card-header">
          <h3>角色管理</h3>
          <el-button type="primary" @click="handleAdd" v-if="isAdmin">
            <el-icon><Plus /></el-icon>
            添加角色
          </el-button>
        </div>
      </template>

      <el-table
        :data="roles"
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="name" label="角色名称" />
        <el-table-column prop="code" label="角色代码" />
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column prop="user_count" label="用户数量" width="100" align="center" />
        <el-table-column prop="is_system" label="系统角色" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.is_system ? 'success' : 'info'" size="small">
              {{ row.is_system ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                type="primary"
                link
                :disabled="!isAdmin || row.is_system"
                @click="handleEdit(row)"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                link
                :disabled="!isAdmin || row.is_system"
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 角色表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加角色' : '编辑角色'"
      width="500px"
      :close-on-click-modal="false"
      @close="resetForm"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="rules"
        label-width="100px"
        :validate-on-rule-change="false"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input 
            v-model="roleForm.name" 
            placeholder="请输入角色名称"
            :maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="角色代码" prop="code">
          <el-input 
            v-model="roleForm.code" 
            placeholder="请输入角色代码"
            :maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            placeholder="请输入角色描述"
            :maxlength="200"
            show-word-limit
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="权限配置" prop="permissions">
          <el-tree
            ref="permissionTree"
            :data="permissionOptions"
            show-checkbox
            node-key="id"
            :props="{ label: 'name' }"
            @check="handlePermissionChange"
            :default-checked-keys="Array.isArray(roleForm.permissions?.checkedKeys) ? roleForm.permissions.checkedKeys : []"
            :default-expanded-keys="['user', 'role', 'movie']"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, shallowRef, watch, nextTick } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import { useDebounceFn } from '@vueuse/core'
import { useUserStore } from '@/stores/user'
import { debounce } from 'lodash-es'

const userStore = useUserStore()
const isAdmin = computed(() => userStore.user?.is_admin || false)

// 状态变量
const loading = ref(false)
const roles = ref([])
const dialogVisible = ref(false)
const dialogType = ref('add')
const submitting = ref(false)

// 表单相关
const roleFormRef = ref(null)
const roleForm = ref({
  name: '',
  code: '',
  description: '',
  permissions: {
    checkedKeys: [],
    halfCheckedKeys: []
  }
})

const rules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色代码', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ]
}

// 权限树相关
const permissionTree = ref(null)
const permissionOptions = shallowRef([
  {
    id: 'user',
    name: '用户管理',
    children: [
      { id: 'user_view', name: '查看用户' },
      { id: 'user_edit', name: '编辑用户' },
      { id: 'user_delete', name: '删除用户' }
    ]
  },
  {
    id: 'role',
    name: '角色管理',
    children: [
      { id: 'role_view', name: '查看角色' },
      { id: 'role_edit', name: '编辑角色' },
      { id: 'role_delete', name: '删除角色' }
    ]
  },
  {
    id: 'movie',
    name: '电影管理',
    children: [
      { id: 'movie_view', name: '查看电影' },
      { id: 'movie_edit', name: '编辑电影' },
      { id: 'movie_delete', name: '删除电影' }
    ]
  }
])

// 方法
const fetchRoles = async () => {
  try {
    loading.value = true
    const response = await request.get('/api/roles/')
    if (response.status === 'success') {
      // 添加用户数量字段
      roles.value = response.data.map(role => ({
        ...role,
        user_count: role.user_count || 0
      }))
    } else {
      throw new Error(response.message || '获取角色列表失败')
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  nextTick(() => {
    resetForm()
  })
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  nextTick(() => {
    roleForm.value = {
      ...row,
      permissions: {
        checkedKeys: Array.isArray(row.permissions) ? row.permissions : [],
        halfCheckedKeys: []
      }
    }
  })
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色"${row.name}"吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await request.delete(`/api/role/${row.id}/delete/`)
    if (response.data.status === 'success') {
      ElMessage.success('删除成功')
      fetchRoles()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除角色失败:', error)
      ElMessage.error('删除角色失败')
    }
  }
}

const handleSubmit = async () => {
  if (!roleFormRef.value) return
  
  try {
    await roleFormRef.value.validate()
    submitting.value = true
    
    const requestData = {
      name: roleForm.value.name,
      code: roleForm.value.code,
      description: roleForm.value.description,
      permissions: Array.isArray(roleForm.value.permissions?.checkedKeys) 
        ? roleForm.value.permissions.checkedKeys 
        : []
    }
    
    const method = dialogType.value === 'add' ? 'post' : 'put'
    const url = dialogType.value === 'add' 
      ? '/api/role/create/'
      : `/api/role/${roleForm.value.id}/update/`
    
    const response = await request({
      url,
      method,
      data: requestData
    })
    
    if (response.status === 'success') {
      ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
      dialogVisible.value = false
      fetchRoles()
    } else {
      throw new Error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('表单提交失败:', error)
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else if (error.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('操作失败')
    }
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  if (roleFormRef.value) {
    roleFormRef.value.resetFields()
  }
  roleForm.value = {
    name: '',
    code: '',
    description: '',
    permissions: {
      checkedKeys: [],
      halfCheckedKeys: []
    }
  }
}

// 监听对话框关闭
watch(dialogVisible, (val) => {
  if (!val) {
    resetForm()
  }
})

// 生命周期钩子
onMounted(() => {
  fetchRoles()
})

// 处理权限变更
const handlePermissionChange = debounce((checkedKeys, { halfCheckedKeys }) => {
  roleForm.value.permissions = {
    checkedKeys,
    halfCheckedKeys
  }
}, 300)
</script>

<style scoped>
.role-management {
  padding: 20px;
}

.role-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style> 